package com.surekam.core.rsa;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.interfaces.RSAPublicKey;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import com.surekam.core.rsa.domain.PreLoginRequest;
import com.surekam.core.rsa.domain.PreLoginRequestImpl;

import flexjson.JSONSerializer;

public class Main {
	private static String MODULE = "C79FF85FBD32D15D58815D398184D6042097861860E49AB601C4245E96B88B11811CAF05"
			+ "ABCE9D1ABBD9C4212A633255DE116E3E4FCD9B08CDB6F895176692206B9A9D06B3E48D4D3C2AD7F9"
			+ "9FB36C77B9FD65E23462800A0AE6F7BA5544C5CC46792DD157115A8BDA3311195ABE9A1339D53310"
			+ "7E985873F8ADE15FA4CA4BCF";

	private static final String keyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHn/hfvTLRXViBXTmBhNYEIJeG"
			+ "GGDkmrYBxCRelriLEYEcrwWrzp0au9nEISpjMlXeEW4+T82bCM22+JUXZpIga5qd"
			+ "BrPkjU08Ktf5n7Nsd7n9ZeI0YoAKCub3ulVExcxGeS3RVxFai9ozERlavpoTOdUz" + "EH6YWHP4reFfpMpLzwIDAQAB";

	private static final String API_URL = "https://api.baidu.com/sem/common/HolmesLoginService";

	private static String PUBLIC_EXPONENT = "010001";

	// private static final String text =
	// "{'username':'hn12396','token':'5eeb3eb0c7e6ed9d69f1b4fd838a579e','functionName':'preLogin','uuid':'C80AA99AEC09','request':{'ovVersion':'windows','deviceType':'pc','clientVersion':'1.0'}}";

	public static void main(String[] args) throws Exception {
		Main m = new Main();
		m.client();
		// byte[] compress = GZIP.compress(m.toJson());
		// String unCompress = GZIP.unCompress(compress);
		// System.out.println(unCompress);
	}

	public String toJson() {
		PreLoginRequest request = new PreLoginRequest();
		request.setClientVersion("1.0");
		request.setDeviceType("pc");
		request.setOsVersion("windows");

		PreLoginRequestImpl ri = new PreLoginRequestImpl();
		ri.setUsername("hn12396");
		ri.setToken("35a6601847299d7db0dd98a65966afd6");
		ri.setFunctionName("preLogin");
		ri.setUuid("C80AA99AEC09");
		ri.setRequest(request);

		JSONSerializer serializer = new JSONSerializer();
		String json = serializer.exclude("*.class", "*.id").deepSerialize(ri);
		System.out.println(json);
		return json;
	}

	public void client() throws Exception {
		// list.add(new Header("USERNAME", "hn12396"));
		// list.add(new Header("PASSWORD", "hn12396Aa"));
		// list.add(new Header("TOKEN", "35a6601847299d7db0dd98a65966afd6"));
		// Protocol myhttps = new Protocol("https", new MySecureProtocolSocketFactory(), 443);
		// Protocol.registerProtocol("https", myhttps);

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(API_URL);
		post.addRequestHeader(new Header("UUID", "C80AA99AEC09"));
		post.addRequestHeader(new Header("account_type", "1"));
		post.setRequestHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36");
		post.setRequestHeader(new Header("Content-Type", "data/gzip and rsa public encrypt;charset=UTF-8'"));
		// post.setRequestHeader("Accept-Encoding", "gzip, deflate");
		RSA rsa = new RSA();
		RSAPublicKey publicKey = rsa.loadPublicKey(null);
		// byte[] compress = GZIP.compresser(toJson());
		byte[] compress = getPHPBytes();
		byte[] encrypted = rsa.encrypt(publicKey, compress);
		// byte[] compress = GZIP.compress(text);
		// byte[] encrypted = encrypted(compress);

		// post.setRequestEntity(new ByteArrayEntity(bytes));
		post.setRequestEntity(new ByteArrayRequestEntity(encrypted));

		// post.setRequestHeader("Content-type", "application/octet-stream");
		int method = client.executeMethod(post);
		System.out.println(method);
		System.out.println("=================HEAD===================");
		byte[] respByte = post.getResponseBody();
		Header[] headers = post.getRequestHeaders();
		System.out.println("----------------------request header-------------------");
		for (Header header : headers) {
			System.out.println(header.getName() + "\t" + header.getValue());
		}
		System.out.println("----------------------request header-------------------");

		Header[] responseHeaders = post.getResponseHeaders();
		for (int i = 0; i < responseHeaders.length; i++) {
			System.out.println(responseHeaders[i].getName() + "\t" + responseHeaders[i].getValue());
		}
		System.out.println("=================BODY===================");
		for (int i = 0; i < respByte.length; i++) {
			System.out.print(respByte[i] + "  ");
		}
		System.out.println();
	}

	public byte[] getPHPBytes() throws Exception {
		HttpClient client = new HttpClient();
		GetMethod get = new GetMethod("http://localhost/dataapi/demo.php");
		get.addRequestHeader(new Header("Accept-Encoding", "gzip"));
		int status = client.executeMethod(get);
		// System.out.println("状态为：" + status);
		// String is = get.getResponseBodyAsString();
		// System.out.println(is);
		byte[] responseBody = get.getResponseBody();
		byte[] buf = new byte[1024];
		InputStream is = get.getResponseBodyAsStream();
		byte[] inputStreamToByte = InputStreamToByte(is);
		
		return inputStreamToByte;
	}

	private byte[] InputStreamToByte(InputStream is) throws IOException {
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		int ch;
		while ((ch = is.read()) != -1) {
			bytestream.write(ch);
		}
		byte imgdata[] = bytestream.toByteArray();
		bytestream.close();
		return imgdata;
	}
}

/**
 * 6.2登录服务响应消息头 return code参考 Code值 含义 0 OK: 成功 2 INVALID_ENCODING: 请求数据的编码错 误，非 UTF-8 3 DAMAGED_DATA: 请求数据损坏 4
 * DATA_TOO_LARGE: 请求数据过大
 */

